from django import newforms as forms
from django.newforms import BaseForm
from google.appengine.ext import db

from gaev import exceptions
from gaev import utils


def prop_to_field(property):
	defaults = {'required': property.required, 'label': property.get_caption()}
	if isinstance(property, db.StringProperty):
	    return forms.CharField(defaults)
	elif isinstance(property, db.IntegerProperty):
		return forms.IntegerField(defaults)
	elif isinstance(property, db.FloatProperty):
		return forms.CharField(defaults)
	elif isinstance(property, db.BooleanProperty):
		return forms.BooleanField(defaults)
	else:
	    return None

def get_initial_values(entity):
	from gaev import HumanizeContext
	return entity.get_humanized_properties(HumanizeContext(use_html=False))

class ModelForm(BaseForm):
	base_fields={}
	
	def __init__(self, model=None, entity=None, data=None, auto_id='id_%s', prefix=None, initial=None):
		if entity:
			self.entity = entity
			self.model = model = entity.__class__
			initial=get_initial_values(entity)
		elif model:
			self.entity = None
			self.model = model
		else:
			raise exceptions.InsufficientArgumentsError()

		BaseForm.__init__(self, data, auto_id, prefix, initial)
			
		props=model.properties()
		fields=[]
		for prop_id in props:
			prop=props[prop_id]
			fld=prop_to_field(prop)
			if fld==None:
				continue
			fields.append((prop_id, fld))
		self.fields=utils.SortedDictFromList(fields)
		
	def save(self):
		if not self.is_valid():
			raise exceptions.SavingInvalidFormError()
		data=self.clean_data
		if self.entity:
			entity=self.entity
			
			for field in data:
				setattr(entity,  field,  data[field])
		else:
			entity=self.model(**data)
		entity.put()
		
		self.entity=entity
